<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    switchFullscreen
    @ok="handleOk"
    :okButtonProps="{ class:{'jee-hidden': disableSubmit} }"
    @cancel="handleCancel"
    cancelText="关闭">
      <div>
        <a-form-item label="经纬度">
          <a-input v-model="form.location" readonly placeholder="请点击右侧按钮选点" style="width: 300px" />
          <a-button type="primary" icon="environment" @click="openMap">选点</a-button>
        </a-form-item>
        <a-modal title="选择位置" :visible="visible" @ok="handleOk" @cancel="handleCancel" width="800px" >
          <div style="margin-bottom: 8px">
            <a-input-search placeholder="搜索位置" enter-button @search="handleSearch" />
          </div>
          <div id="map-container" style="width: 100%; height: 500px;"></div>
          <div >
              名称：<font color='blue'>{{address.name}} </font> 地址：<font color='blue'>{{address.address}}</font> 经度：<font color='blue'>{{address.lonlat}} </font>
          </div>
        </a-modal>
      </div>
  </j-modal>
</template>

<script>
export default {
  data() {
    return {
      title:'',
      width:800,
      visible: false,
      disableSubmit: false,
      form: {
        location: ''
      },
      map: null,
      marker: null,
      searchService: null,
      selectedPoint: null,
      searchlocation:[],
      address:{
        name:'',
        address:'',
        lonlat:''
      }
    };
  },
  methods: {
    show(model){
      this.searchlocation = [];
      console.log("selectedPoint:",JSON.stringify(model));
      
      this.openMap(model);
    },
    openMap(model) {
      this.visible = true;
      this.$nextTick(() => {
          this.initMap(model);
      });
    },
    handleOk() {
      if (this.address.name && this.address.lonlat) {
        this.form.location = `${this.selectedPoint.lng},${this.selectedPoint.lat}`;
      }else{
        this.form.location = '';
        this.$message.error('请选择地图上的点');
        return;
      }
      this.visible = false;
      this.$emit('ok', this.address);
    },
    handleCancel() {
      this.visible = false;
    },
    initMap(model) {
        let lng = 116.40769,lat = 39.89945;
        if(model.id){
          lat = model.shopLat;
          lng = model.shopLng;
        }
        this.map = new T.Map('map-container');
        this.map.centerAndZoom(new T.LngLat(lng, lat), 12);
        this.map.enableScrollWheelZoom();
        var geocode = new T.Geocoder();
        this.map.addEventListener('click', (e) => {
          geocode.getLocation(e.lnglat,this.searchResult);
          this.moveToCenter(e.lnglat)
        });
        if(model.id){
          var address = {"address":model.shopAddress,"name":model.shopName,"lonlat":lng+','+lat}
          this.address = address;
          this.setMarker(address)
        }
    },
    searchResult(result) {
        let name = result.addressComponent.poi
        let addr = result.formatted_address
        let lonlat = result.location.lon+","+result.location.lat
        var address = {"address":addr,"name":name,"lonlat":lonlat}
        this.setMarker(address)
        this.address = address;

    },
    setMarker(address) {
      let lnglatArr = address.lonlat.split(',')
      let lnglat = new T.LngLat(lnglatArr[0], lnglatArr[1])
      var marker = new T.Marker(lnglat);
      marker.addEventListener('click', (e) => {
        this.address = address;
        this.moveToCenter(e.lnglat)
      });
      marker.addEventListener('dblclick', (e) => {
        this.address = address;
        this.map.removeOverLay(marker);
        this.address = {name:'',address:'',lonlat:''}
      });
      this.map.addOverLay(marker);
      this.selectedPoint = lnglat;
    },
    moveToCenter(lnglat) {
      this.map.centerAndZoom(lnglat, 17);
    },  
    handleSearch(keyword) {
      let config = {
        pageCapacity: 10, //每页显示的数量
        onSearchComplete: this.localSearchResult, //接收数据的回调函数
      }
      this.localsearch = new T.LocalSearch(this.map, config)
      this.localsearch.search(keyword, 1)
    },
    localSearchResult(res) {
      const { pois } = res
      this.searchlocation = pois
      //坐标数组，设置最佳比例尺时会用到
      var zoomArr = [];
      if (pois === false) {
        this.addressArr === []
      } else {
        this.addressArr = pois
        for (let i = 0; i < pois.length; i++) {
          let address = pois[i];
          let lnglatArr = address.lonlat.split(',')
          console.log("address:",address);
          let lnglat = new T.LngLat(lnglatArr[0], lnglatArr[1])
          if(i==0){
            this.map.centerAndZoom(lnglat, 16);
          }
          zoomArr.push(lnglat);
          this.setMarker(address);
        }
        //显示地图的最佳级别
        this.map.setViewport(zoomArr);
      }
    },
    handleCancel () {
      this.close()
    },
    close () {
      this.$emit('close');
      this.visible = false;
    },
  }
};
</script>
